<template>
  <div id="discuss">
    <div class="row" :style="{ marginBottom: '24px' }">
      <div class="text-right col">
        <el-button @click="dialogVisible = true" size="default" type="primary">贡献题解</el-button>
      </div>
    </div>
    <div class="QxT4hD">
      <span class="_2R7vBo">{{ count }}条题解</span>
    </div>
    <el-container class="user border-bottom" :style="{ marginBottom: '24px', paddingBottom: '12px' }"
      v-for="(v, key) in usersolution" :key="key">
      <el-aside width="40px" class="imag">
        <router-link v-slot="{ navigate }" custom :to="{
      name: '用户',
      query: { userid: v.userid },
    }">
          <el-avatar size="default" @click="navigate" :src="v.user?.headportrait"></el-avatar>
        </router-link>

      </el-aside>
      <el-main class="context">
        <header class="row">
          <div class="col username">
            <router-link v-slot="{ href }" custom :to="{
      name: '用户',
      query: { userid: v.userid },
    }">
              <el-link :href="href">{{ v.user?.name }}
              </el-link>
            </router-link>
          </div>
          <div class="text-right" :style="{ width: '200px' }">

            <!-- <el-button type="danger" size="default" text>删除
            </el-button> -->
          </div>
          <div class="text-right" v-if="v.userid === user.ID" :style="{ width: '60px' }">
            <span :style="{ color: '#000', cursor: 'pointer' }" @click="update(v)" text>修改
            </span>
            <!-- <el-popover trigger="click" placement="top" :width="160">
              <div style="text-align: center; margin: 0">
                <el-button size="small" type="primary" @click="handleCommand('a', v.ID, !v.top)">删除</el-button>
                <el-button size="small" @click="handleCommand('b', v.ID, !v.top)">{{ v.top ? "取消置顶" : "置顶" }}
                </el-button>
              </div>
              <template #reference>
                <el-icon class="icon1">
                  <MoreFilled />
                </el-icon>
              </template>
</el-popover> -->
          </div>
        </header>
        <div class="text-html">
          <div v-html="v.context" class="editor-content-view"></div>
        </div>
        <pre :class="'language-' + v.lang">
  <code v-text="v.code" />
</pre>
        <div>
          <span v-text="TimeYH(v.createdAt)"></span>
        </div>
      </el-main>
    </el-container>
    <el-dialog v-model="dialogVisible" class="my_el-dialog__body" title="提交题解" width="960px">
      <div class="row">
        <div class="col">
          <div>
            感谢您为这道题贡献题解！~\(≥▽≤)/~。题解需有解题思路和题解代码，请勿抄袭题解。

          </div>
          <div>
            为了保证题解质量，您提交的题解我们会在第一时间进行审核，通过后会展示在这里，为其他同学提供解题思路。

          </div>
        </div>
        <div class="col-2 text-right">
          <el-popover placement="left-start" :width="450" trigger="click">
            <template #reference>
              <el-button class="disbutton" size="default">
                审核规则 &nbsp;
                <el-icon :size="16">
                  <QuestionFilled />
                </el-icon>
              </el-button>
            </template>
            <div>
              <div>题解审核将根据以下规则：</div>
              <div>1）思路详细：有详细解题思路，并能匹配提交代码的；</div>
              <div>2）格式明晰：编辑文本公式无错乱、源码格式无错乱等；</div>
              <div>3）内容与题解相关：例如求赞求转发而没有题解内容的不可以哦；</div>
              <div>4）无重复题解：当前公开题解中没有与提交题解完全一致的；</div>
              <div>5）未抄袭题解：若抄袭本网站其他用户或其他网站题解</div>
              <div>如对某题目有疑问，可以添加网站右上角助教老师沟通。</div>
              <br>
              <div>每贡献一个题解并审核通过，+10贡献积分，+10金币。</div>
              <div>贡献积分会持续累加，不会消耗。</div>
            </div>
          </el-popover>

        </div>
      </div>
      <div class="row">
        <div class="col">
          <div>
            <label for="Wangeditor" :style="{ height: '42px', lineHeight: '42px' }">解题思路： </label>
            <Wangeditor id="Wangeditor" ref="Wangeditor1" v-bind="{
      height: '250px', context: usersolutionfrom.htmlcontext, mode: 'simple'
    }">
            </Wangeditor>
          </div>
        </div>
        <div class="col">
          <div>
            <label for="MonaoEditor">代码： </label>
            <el-select size="small" v-model="usersolutionfrom.lang" class="m-2" placeholder="请选择语言">
              <el-option label="C/C++" value="CPP" />
              <el-option label="Python" value="python" />
            </el-select>
          </div>
          <div>
            <MonaoEditor id="MonaoEditor" :style="{ height: '371px', border: '1px solid rgb(204, 204, 204)' }"
              ref="ditor1" :value="usersolutionfrom.code" v-bind="{ language: usersolutionfrom.lang }" @change="change">
            </MonaoEditor>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button size="default" @click="dialogVisible = false">取消</el-button>
          <el-button size="default" v-loading="loading" type="primary" @click="submit({ pid: null })">贡献题解</el-button>
        </span>
      </template>
    </el-dialog>
    <div class="m-p-6 text-right">
      <el-pagination :page-size="limit" :total="count" @current-change="(r) => (offset = limit * (r - 1))"
        layout="prev, pager, next" :current-page="Math.floor(offset / limit) + 1"></el-pagination>
    </div>
  </div>
</template>
<script setup lang="ts">
import { QuestionFilled } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox, ElPagination } from "element-plus";
import highlight from 'highlight.js';
import * as monaco from "monaco-editor";
import { assign } from "underscore";
import { h, nextTick, onMounted, reactive, ref, watch } from "vue";
import {
  asynccreatedorupdateusersolution,
  asyncselectusersolution
} from "../../../api";
import MonaoEditor from "../../../components/MonaoEditor.vue";
import Wangeditor, { Emenu } from "../../../components/wangeditor.vue";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { TimeYH } from '../../../util/time';

const props = defineProps<{ ID?: number, user: Studycodemodel.Iuser, question?: Studycodemodel.Iquestion }>()
const menu: Emenu = [
  "head", // 标题
  "fontSize", // 字号
  "fontName", // 字体
  "italic", // 斜体
  "strikeThrough", // 删除线
  "foreColor", // 文字颜色
  "backColor", // 背景颜色
  "link", // 插入链接
  "justify", // 对齐方式
  "quote", // 引用
  "emoticon", // 表情
  "image", // 插入图片
  "code", // 插入代码
  "undo", // 撤销
  "redo", // 重复
]

const usersolution = ref<Studycodemodel.Iusersolution[]>([])
const input = ref('')
const inputkey = ref<number | null>(null)
const count = ref(0)
const offset = ref(0)
const limit = ref(10)
const height = ref("152px")
const dialogVisible = ref(false)
const Toolbarshow = ref(false)


function update(v: Studycodemodel.Iusersolution) {
  Object.assign(usersolutionfrom, v)
  dialogVisible.value = true
}

const usersolutionfrom = reactive<Studycodemodel.Iusersolution>({
  context: '',
  htmlcontext: '',
  lang: 'CPP'
})



onMounted(() => {
  start()
  const v = localStorage.getItem(`usersolution_${props.ID}`)
  if (v) {
    const data = JSON.parse(v)
    Object.assign(usersolutionfrom, data)
  }
})



watch(() => props.ID, () => {
  localStorage.setItem(`usersolution_${props.ID}`, JSON.stringify(usersolutionfrom))
  start()
})

watch(() => offset.value, start)

async function start() {
  try {
    const data = await asyncselectusersolution({
      questionid: props.ID ? props.ID : 0,
      _limit: limit.value,
      _offset: offset.value,
      _order: ["top", "ID"],
      state: 1
    });
    count.value = data.count;
    usersolution.value = data.rows;
  } catch (e: any) {
    console.log(e);
  }
  nextTick(() => {
    highlight.highlightAll()
  })
}

function change(v?: string, e?: monaco.editor.IModelContentChangedEvent) {
  if (e) {
    usersolutionfrom.code = v ? v : '';
  }
}

const Wangeditor1 = ref()
const ditor1 = ref()

const loading = ref(false)
async function submit({ pid }: any) {
  const editor: any = Wangeditor1.value;
  const html: string = editor.syncHTML();
  const text: string = editor.gettext();
  const htmlcontext: string = editor.getcontext();
  if (text.length < 5) {
    ElMessage.error("解题思路过少");
    return;
  }
  try {
    loading.value = true
    await asynccreatedorupdateusersolution(assign(usersolutionfrom, {
      pid,
      context: html,
      questionid: props.ID ? props.ID : 0,
      htmlcontext,
      text,
    }));
    ElMessage.success("提交成功");
    editor.removeNodes();
    usersolutionfrom.context = ''
    usersolutionfrom.code = ''
    usersolutionfrom.htmlcontext = ''
    loading.value = false
    ElMessageBox({
      title: '提交成功',
      message: h('p', null, [
        h('img', { src: 'https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/JOY/image/Banner_1', width: '488' }),
        h('span', null, '我们会在24小时内审核完成，通过后会进行公开展示并增加您的贡献积分。'),
        h('br', null, ''),
        h('br', {}, ''),
        h('span', {}, '贡献将按照以下规则：'),
        h('br', {}, ''),
        h('span', {}, '1）测试点正确：测试点需要完全符合题目要求、确保正确；'),
        h('br', {}, ''),
        h('span', {}, '2）测试点无重复：当前已有测试点中，没有完全重复或基本重复的测试点。'),
        h('br', {}, ''),
        h('span', {}, '3）内容与题解相关：例如求赞求转发而没有题解内容的不可以哦；'),
        h('br', {}, ''),
        h('span', {}, '4）无重复题解：当前公开题解中没有与提交题解完全一致的；'),
        h('br', {}, ''),
        h('span', {}, '5）未抄袭题解：若抄袭本网站其他用户或其他网站题解。'),
        h('br', {}, ''),
        h('br', {}, ''),
        h('span', {}, '如对测试点有疑问，可以添加网站右上角助教老师沟通。'),

      ]),
      confirmButtonText: '好的',
      customStyle: {
        'width': '520px'
      },
      callback: () => {
        dialogVisible.value = false
      },
      buttonSize: 'default'
    })

  } catch (e: any) {
    loading.value = false
    ElMessage.error(e);
  }
  start();
}
</script>

<style scoped>
.pd {
  padding-top: 24px;
  padding-bottom: 24px;
  width: 80px;
}

.QxT4hD {
  margin-bottom: 24px;
  padding-left: 12px;
  font-size: 14px;
  background: #f5f5f5;
  border-radius: 2px;
  height: 48px;
  line-height: 48px;
  color: #000;
}

.icon {
  font-size: 20px;
  color: var(--color-AAAAAA);
}

.cu {
  cursor: pointer;
  display: inline-block;
  margin-right: 26px;
  font-size: 14px;
}

.text-aa {
  color: var(--color-AAAAAA);
}

.context {
  padding-top: 1px;
  padding-bottom: 1px;
  padding-left: 15px;
  padding-right: 15px;
}

.context header {
  color: var(--color-43);
}

.wang {
  height: 165px;
}

.username {
  font-size: 14px;
  color: #8c8c8c;
}

.text-sm-right {
  font-size: 12px;
  color: var(--color-8898AA);
  text-align: right;
}

.input-f {
  margin-top: 3px;
  margin-bottom: 3px;
}

.text-html {
  font-size: 14px;
}

.text-icon-a {
  min-height: 40px;
  font-size: 14px;
  padding-top: 12px;
}

.text-icon-a span {
  display: inline-block;
  margin-right: 26px;
}

.icon1 {
  transform: rotate(90deg);
}

.icon-t:hover {
  color: var(--color-cheng);
}

.icon-tn {
  color: var(--color-cheng);
}

#discuss {
  padding: 15px;
}

.disbutton {
  border: none;
  background-color: #f5f5f5;
  --el-button-hover-color: "#000";
  --el-button-hover-background-color: #f5f5f5;
  height: 28px;
  line-height: 28px;
  padding-top: 0;
  padding-bottom: 0;
  padding-left: 12px;
  padding-right: 12px;
}
</style>

<style>
#discuss p {
  margin-bottom: 0px;
}

.slider-mouseover {
  border-left: 1px solid rgb(204, 204, 204);
}

.my_el-dialog__body .el-dialog__body {
  padding-top: 0px;
}
</style>